package com.health.db.service.order.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alipay.api.AlipayApiException;
import com.health.db.dao.order.IMedicalTreatRecordDao;
import com.health.db.dao.order.IRegisterOrderActionDao;
import com.health.db.dao.order.IRegisterOrderDao;
import com.health.db.dao.order.IRegisterOrderZProcessDao;
import com.health.db.dao.order.IRegisterOrderZScheduleDao;
import com.health.db.dao.user.IGoodsPriceListDao;
import com.health.db.dao.user.IPatientListDao;
import com.health.db.dao.user.IStuffSortDao;
import com.health.db.dao.user.IUserAccountJournalDao;
import com.health.db.dao.user.IUserAccountLedgerDao;
import com.health.db.dao.user.IUserCardJournalDao;
import com.health.db.dao.user.IUserCardListDao;
import com.health.db.dao.user.IUserLISTDao;
import com.health.db.model.EPayCashPayment;
import com.health.db.model.MedicalTreatRecordWithBLOBs;
import com.health.db.model.RegisterOrder;
import com.health.db.model.RegisterOrderAction;
import com.health.db.model.RegisterOrderExample;
import com.health.db.model.RegisterOrderZProcess;
import com.health.db.model.RegisterOrderZSchedule;
import com.health.db.model.UserAccountJournal;
import com.health.db.model.UserAccountLedger;
import com.health.db.model.UserCardJournal;
import com.health.db.model.UserCardList;
import com.health.db.model.UserCardListExt;
import com.health.db.model.UserLIST;
import com.health.db.service.order.IEPayCashPaymentService;
import com.health.db.service.order.IRegisterOrderService;
import com.health.db.service.sm.IAlipayService;
import com.health.db.service.sm.IRongService;
import com.health.db.service.sm.IWXPayService;
import com.health.db.service.user.IUserCardListService;
import com.health.mapp.service.SpringContextUtil;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.DateUtils;
import com.health.mapp.utils.PropertiesUtil;
import com.health.pay.tencent.protocol.refund.RefundReqData;
import com.health.pay.tencent.protocol.refund.RefundResData;

public class RegisterOrderServiceImpl implements IRegisterOrderService {


	private IRegisterOrderDao registerOrderDao;
	
	private IMedicalTreatRecordDao  medicalTreatRecordDao ;
	
	private IRegisterOrderActionDao registerOrderActionDao;
	
	private IUserCardListDao userCardListDao;

	private IUserAccountLedgerDao userAccountLedgerDao ;
	
	private IUserAccountJournalDao userAccountJournalDao ;
	
	private IUserLISTDao userLISTDao;
	
	private IPatientListDao patientListDao;
	
	private IGoodsPriceListDao goodsPriceListDao;
	
	private IUserCardJournalDao userCardJournalDao;
	
	private IRegisterOrderZScheduleDao registerOrderZScheduleDao;
	
	private IRegisterOrderZProcessDao registerOrderZProcessDao;
	
	private IStuffSortDao stuffSortDao;

	public IStuffSortDao getStuffSortDao() {
		return stuffSortDao;
	}

	public void setStuffSortDao(IStuffSortDao stuffSortDao) {
		this.stuffSortDao = stuffSortDao;
	}



	/**
	 * @return the registerOrderZProcessDao
	 */
	public IRegisterOrderZProcessDao getRegisterOrderZProcessDao() {
		return registerOrderZProcessDao;
	}



	/**
	 * @param registerOrderZProcessDao the registerOrderZProcessDao to set
	 */
	public void setRegisterOrderZProcessDao(
			IRegisterOrderZProcessDao registerOrderZProcessDao) {
		this.registerOrderZProcessDao = registerOrderZProcessDao;
	}



	@Override
	public List<RegisterOrder> selectSimple(RegisterOrderExample example) {
		List<RegisterOrder>  registerOrderTempList =new ArrayList<RegisterOrder>();
		
		List<RegisterOrder> registerOrderTempLists= null;
		
		//只有医生查询新订单的时候 去单独查询抢单池
		if (null!=example.getAccepterid()&&
				null!=example.getCommonOrderIds()&&
				0!=example.getCommonOrderIds().size()&&
				null!=example.getRunstatusid()&&
				example.getRunstatusid().intValue()==Constant.CONSTANTS_ORDER_RUNSTATUS_ID_2.intValue()&&
				0==example.getOffset()
				) {
			registerOrderTempLists= registerOrderDao.selectSimpleOrderGrapPool(example);
			example.setCommonOrderIds(null);
		}
	
		registerOrderTempList = registerOrderDao.selectSimple(example);
		
		
		if (null!=registerOrderTempLists&&registerOrderTempLists.size()>0) {
			registerOrderTempList.addAll(registerOrderTempLists);
		}
		return registerOrderTempList;
	}

	 
	
	

	@Override
	public RegisterOrderExample insertOrder(RegisterOrder record,
			MedicalTreatRecordWithBLOBs patRecord) {
 
		RegisterOrderExample order = new RegisterOrderExample();
		 
		//非预约类
		 if (!(record.getRegistertypeid().intValue()==Constant.CONSTANTS_ORDER_TYPE_ID_1.intValue()||
				 record.getRegistertypeid().intValue()==Constant.CONSTANTS_ORDER_TYPE_ID_4.intValue())){
			//查看已经约的数量
			int Order_ScheduleSize_BOUND= Integer.valueOf(PropertiesUtil.getString("Order_ScheduleSize_BOUND"));
			RegisterOrderZSchedule registerOrderZSchedule =new RegisterOrderZSchedule();
			registerOrderZSchedule.setAccepterid(record.getAccepterid());
			registerOrderZSchedule.setOrderTimeSolt(Short.valueOf( record.getComment()));
			registerOrderZSchedule.setScheduleDate(DateUtils.formatDate(record.getScheduleTime()));
			registerOrderZSchedule.setCreateDate(new Date(DateUtils.now().getTime()-15*60*1000));
			int size = registerOrderZScheduleDao.countScheduleSize(registerOrderZSchedule);
			if(size>=Order_ScheduleSize_BOUND){
				order.setUpdateNum(Constant.Schedule_Flag);
				return order;
			}
		}
		int freeType=record.getOrderfeetypeid();
		
		
 
		int result=-1;
		result= registerOrderDao.insert(record);
		patRecord.setRegisterid(record.getRegisterid());
		medicalTreatRecordDao.insert(patRecord);
	 
		order.setUserid(record.getUserid());
		
		//更新成功数目
		order.setUpdateNum(result);
		//提取插入的主键
		order.setRegisterid(record.getRegisterid());
		order.setPatRecordId(patRecord.getMedicaltreatid());
		  
		//处理，不知道这个是做什么的，怎么和病历一样的Id
		order.setRefbillid(patRecord.getMedicaltreatid());
		//更新 用户 患者 价格
		//并没有更新orderblilltime
		registerOrderDao.updateOrderSelective(order);
		
		
		//确认插入正确
		if (order.getUpdateNum()==1) {
			   
	        
	        int actionMethod =-1;
	        
	        if (freeType==Constant.CONSTANTS_ORDER_FREE_ID_0) {
	        	actionMethod= Constant.CONSTANTS_ORDER_ACTION_ID_9;
			}else{
				actionMethod= Constant.CONSTANTS_ORDER_ACTION_ID_1;
			}
	        
	        //插入订单日志
	        delayOrderActionRecord(order.getRegisterid(),actionMethod,order.getUserid());
		}
		
		
		 if (!(record.getRegistertypeid().intValue()==Constant.CONSTANTS_ORDER_TYPE_ID_1.intValue()||
				 record.getRegistertypeid().intValue()==Constant.CONSTANTS_ORDER_TYPE_ID_4.intValue())){
			  
			RegisterOrderZSchedule schedule = new RegisterOrderZSchedule();
			schedule.setUserid(record.getUserid());
			schedule.setAccepterid(record.getAccepterid());
			schedule.setStartTime(record.getScheduleTime());
			schedule.setScheduleDate(DateUtils.formatDatetime(record.getScheduleTime(),"yyyy-MM-dd"));
			schedule.setOrderTimeSolt(Short.valueOf(record.getComment()));
			schedule.setOrderTime((short) record.getScheduleDuration().intValue());
			schedule.setRegisterid(record.getRegisterid());
			schedule.setStatus(Constant.CONSTANTS_NOT_CONFIM);
			registerOrderZScheduleDao.insert(schedule);
		  }
		
		return order;
	}

		

	@Override
	public RegisterOrderExample updateOrder(RegisterOrder record,
			MedicalTreatRecordWithBLOBs patRecord) {
 
		RegisterOrderExample order = new RegisterOrderExample();
		 
		int result=-1;
		//result= registerOrderDao.updateOrderSelective(record);
		medicalTreatRecordDao.deleteByOrderId(record.getRegisterid());
		patRecord.setRegisterid(record.getRegisterid());
		
		medicalTreatRecordDao.insert(patRecord);
	 
		order.setUserid(record.getUserid());
		
		//提取插入的主键
		order.setRegisterid(record.getRegisterid());
		order.setPatRecordId(patRecord.getMedicaltreatid());
		  
		//处理，不知道这个是做什么的，怎么和病历一样的Id
		order.setRefbillid(patRecord.getMedicaltreatid());
		//更新 用户 患者 价格
		//并没有更新orderblilltime
		result=  registerOrderDao.updateOrderSelective(record);
		
		//更新成功数目
		order.setUpdateNum(result);
		
		return order;
	}
	 
	
	

	@Override
	public RegisterOrderExample insertHealthRecordOrder(RegisterOrder record) {
 
		RegisterOrderExample order = new RegisterOrderExample();
		 
		int result=-1;
		result= registerOrderDao.insert(record);
		
		order.setUserid(record.getUserid());
		
		//更新成功数目
		order.setUpdateNum(result);
		//提取插入的主键
		order.setRegisterid(record.getRegisterid());
		//确认插入正确
		if (result==1) {
			   
	        //插入订单日志
	        delayOrderActionRecord(order.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_14,order.getUserid());
		}
		
		return order;
	}

		
		
		/**
		 * 延时处理更新register_order_action表
		 */
		private void delayOrderActionRecord(long orderId, int type,long userId) {

			// 查看用户表相关信息
			Long docId = userId;
			UserLIST userLIST = userLISTDao.selectByUserId(docId);
			RegisterOrderAction registerOrderAction = new RegisterOrderAction();
			registerOrderAction.setRegisterid(Long.valueOf(orderId));
			registerOrderAction.setOperatorid(docId);
			registerOrderAction.setCreateUserid(docId);
			registerOrderAction.setOperatorName(userLIST.getUserNo() + "|"+ userLIST.getUserName());
			
			if (type==Constant.CONSTANTS_ORDER_ACTION_ID_1) {
				//草稿->待支付
				registerOrderAction.setActionName(Constant.CONSTANTS_ORDER_ACTION_DES_1);
				registerOrderAction.setDoendStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_1);
			} else if (type == Constant.CONSTANTS_ORDER_ACTION_ID_2) {
				//支付->待就诊
				registerOrderAction.setActionName(Constant.CONSTANTS_ORDER_ACTION_DES_2);
				registerOrderAction.setDoendStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_2);
			} else if (type == Constant.CONSTANTS_ORDER_ACTION_ID_3) {
				//接诊->就诊中
				registerOrderAction.setActionName(Constant.CONSTANTS_ORDER_ACTION_DES_3);
				registerOrderAction.setDoendStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_3);
			} else if (type == Constant.CONSTANTS_ORDER_ACTION_ID_4) {
				//结诊->待评价
				registerOrderAction.setActionName(Constant.CONSTANTS_ORDER_ACTION_DES_4);
				registerOrderAction.setDoendStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_4);
			} else if (type == Constant.CONSTANTS_ORDER_ACTION_ID_5) {
				//评价->已完成(此流程目前也不会走了，评价只是单纯的评价，不会再引起订单流程变动)
				registerOrderAction.setActionName(Constant.CONSTANTS_ORDER_ACTION_DES_5);
				registerOrderAction.setDoendStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_5);
			} else if (type == Constant.CONSTANTS_ORDER_ACTION_ID_6) {
				//此流程目前不会走，没有拒单
				//拒单->已关闭
				registerOrderAction.setActionName(Constant.CONSTANTS_ORDER_ACTION_DES_6);
				registerOrderAction.setDoendStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_6);
			}else if (type == Constant.CONSTANTS_ORDER_ACTION_ID_9) {
				//免费->待就诊
				registerOrderAction.setActionName(Constant.CONSTANTS_ORDER_ACTION_DES_9);
				registerOrderAction.setDoendStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_2);
		 
		    }else if (type == Constant.CONSTANTS_ORDER_ACTION_ID_7) {
		    	//退款->退款中
		    	registerOrderAction.setActionName(Constant.CONSTANTS_ORDER_ACTION_DES_7);
		    	registerOrderAction.setDoendStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_7);
		    
		    }else if (type == Constant.CONSTANTS_ORDER_ACTION_ID_8) {
				//关闭（取消订单）->已关闭
				registerOrderAction.setActionName(Constant.CONSTANTS_ORDER_ACTION_DES_8);
				registerOrderAction.setDoendStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_6);
			}
		   else if (type == Constant.CONSTANTS_ORDER_ACTION_ID_10) {
				//等待支付->超时关闭(已关闭)
				registerOrderAction.setActionName(Constant.CONSTANTS_ORDER_ACTION_DES_10);
				registerOrderAction.setDoendStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_6);
			}
		   else if (type == Constant.CONSTANTS_ORDER_ACTION_ID_11) {
				//等待就诊->超时退款(已关闭)
				registerOrderAction.setActionName(Constant.CONSTANTS_ORDER_ACTION_DES_11);
				registerOrderAction.setDoendStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_6);
			}
		   else if (type == Constant.CONSTANTS_ORDER_ACTION_ID_12) {
				//就诊中->超时结诊(已完成)
				registerOrderAction.setActionName(Constant.CONSTANTS_ORDER_ACTION_DES_12);
				registerOrderAction.setDoendStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_5);
			}
		   else if (type == Constant.CONSTANTS_ORDER_ACTION_ID_15) {
				//就诊中->超时结诊(已完成)
				registerOrderAction.setActionName(Constant.CONSTANTS_ORDER_ACTION_DES_15);
				registerOrderAction.setDoendStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_2);
			}
			else{
				return;
			}
			
			registerOrderActionDao.insert(registerOrderAction);
		}
		
	@Override
	public int updateOrder4Comment(RegisterOrder record) {

	 
		int result=-1; 
		result=registerOrderDao.updateOrderSelective(record);
 
		delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_5,record.getUserid());
		
		
		return result;
	}

	@Override
	public int updateOrderSelective(RegisterOrder record,int type) {
 
		int result=-1; 
		result= registerOrderDao.updateOrderSelective(record);
 
		
		return result;
	}

	@Override
	public RegisterOrder  selectSimpleSingleByOrderId(Long registerid) {
 
		RegisterOrder   temp =registerOrderDao.selectSimpleSingleByOrderId(registerid);
	  
		
		return temp;
	}

 

	@Override
	public int updateOrder4Accept(RegisterOrder record ) {

		int result=-1; 
		
		//RegisterOrder  currRegisterOrder =registerOrderDao.selectSimpleSingleByOrderIdForUpdate(record.getRegisterid());
		
		RegisterOrder  currRegisterOrder =registerOrderDao.selectSimpleSingleByOrderId(record.getRegisterid());
		if (currRegisterOrder.getRunstatusid().intValue()==Constant.CONSTANTS_ORDER_RUNSTATUS_ID_2.intValue()) {
			
			if (registerOrderDao.orderAcceptLocked(record.getRegisterid(), 0)) {
				result= registerOrderDao.updateOrderSelective(record);
				delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_3,record.getAccepterid());
				
				//解锁
				registerOrderDao.orderAcceptLocked(record.getRegisterid(), 1);
				stuffSortDao.updateOrderCount(record.getAccepterid());
			}else{
				result= -2;
			}
		
		}else{
			result= -2;
		}
		
		return result;
	}

	@Override
	public int updateOrder4Precess(RegisterOrder record ,RegisterOrderZProcess registerOrderZProcess) {

		int result=-1; 
		result= registerOrderDao.updateOrderSelective(record);
		
		registerOrderZProcessDao.insert(registerOrderZProcess);
		
		return result;
	}

	@Override
	public List<RegisterOrder> selectOrderEvaluateByDocId(Long docId) {
		return registerOrderDao.selectSimpleByEvaluate(docId);
	}


	@Override
	public RegisterOrderExample updateOrder4Finish(RegisterOrder record,
			UserAccountLedger userAccountLedger, int type) {

		   RegisterOrderExample order = new RegisterOrderExample();
		   int result=-1;
		  
		    result= registerOrderDao.updateOrderSelective(record);
			if (type==Constant.CONSTANTS_ACCOUNT_EXIST_TYPE_0) {
				userAccountLedgerDao.insertAccountLedger(userAccountLedger);
			}else{
				userAccountLedgerDao.updateBalance(userAccountLedger);
			}
		 
			//提取插入的主键
			order.setAcctpageid(userAccountLedger.getAcctpageid());
			//更新成功数目
			order.setUpdateNum(result);
			////账户类型为0时，
			//if (type==Constant.CONSTANTS_ACCOUNT_EXIST_TYPE_0) {
			//	userAccountLedger.setAcctpageid(order.getAcctpageid());
			//}

			delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_4,record.getAccepterid());
			
			delayUpdateDocAccountJournal(record, record.getAccepterid(), userAccountLedger);
			
			return order;
	}
	
	

	@Override
	public RegisterOrderExample updateOrder4Finish(RegisterOrder record) {

		   RegisterOrderExample order = new RegisterOrderExample();
		   int result=-1;
		  
		    result= registerOrderDao.updateOrderSelective(record);
		
			//更新成功数目
			order.setUpdateNum(result);
	
			delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_4,record.getAccepterid());
			return order;
	}
	/**
	 * record:订单信息
	 * userCardList：用户卡信息
	 * scheduleInfo：预约信息
	 * 
	 */
	@Override
	public RegisterOrderExample updateOrder4CardPayment(RegisterOrder record, UserCardList userCardList,String commont ) {
	
		RegisterOrderExample order = new RegisterOrderExample();
		int result=-1;
		//更新主订单数据
	    result= registerOrderDao.updateOrderSelective(record);
	    //更新card账户数据
	    userCardListDao.updateByPrimaryKeySelective(userCardList);
		//更新成功数目
		order.setUpdateNum(result);
		
		if (result==1) {
		    //插入订单日志
			
			delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_2,record.getUserid());
 
	    	//处理更新卡支付日记账表
			UserCardJournal userCardJournal = new UserCardJournal();
			userCardJournal.setJournalAmount(new BigDecimal(record.getCardJournalAmount()).multiply(new BigDecimal(-1)));
	    	userCardJournal.setCardid(userCardList.getCardid());
	    	userCardJournal.setOwnerid(userCardList.getOwnerid());
	    	userCardJournal.setCarditemid((short)userCardList.getCardtypeid().intValue());
	    	userCardJournal.setJournalDate(new Date());
	    	userCardJournal.setJournalDesc(record.getOrderTypeDesc());
	    	if(null!=record.getGoodsid()){
	    		userCardJournal.setGoodsid(record.getGoodsid().intValue());
	    	}
	    	userCardJournal.setVoucherid(Long.valueOf(record.getRegisterid()));
	    	userCardJournal.setComment(commont);
			
	    	//预约类咨询
	    	if (record.getRegistertypeid().intValue()!=Constant.CONSTANTS_ORDER_TYPE_ID_1.intValue()) {
				
				RegisterOrderZSchedule schedule = new RegisterOrderZSchedule();
				schedule.setRegisterid(record.getRegisterid());
				schedule.setStatus(Constant.CONSTANTS_IS_USERED);
				registerOrderZScheduleDao.updateByPrimaryKeySelective(schedule);
			}
	    	//记录日志
	    	userCardJournalDao.insert(userCardJournal);
	    	delayUpdateUserAccountJournal(record, record.getUserid(),"");
		 
		}
		return order;
	}
	
	
	/**
	 * record:订单信息
	 * userCardList：用户卡信息
	 * scheduleInfo：预约信息
	 * 
	 */
	@Override
	public RegisterOrderExample updateOrder4CardPaymentDoc(RegisterOrder record, UserCardList userCardList,String commont ) {
	
		RegisterOrderExample order = new RegisterOrderExample();
		//扣费金额
		BigDecimal total =record.getRegisterTotal();
		record.setRegisterTotal(null);
		
		int result=-1;
		//更新主订单数据
	    result= registerOrderDao.updateOrderSelective(record);
	    //更新card账户数据
	    userCardListDao.updateByPrimaryKeySelective(userCardList);
		//更新成功数目
		order.setUpdateNum(result);
		
		if (result==1) {
		    //插入订单日志
 
	    	//处理更新卡支付日记账表
			UserCardJournal userCardJournal = new UserCardJournal();
			userCardJournal.setJournalAmount(new BigDecimal(-1).multiply(userCardList.getTemp()));
	    	userCardJournal.setCardid(userCardList.getCardid());
	    	userCardJournal.setOwnerid(userCardList.getOwnerid());
	    	userCardJournal.setCarditemid((short)userCardList.getCardtypeid().intValue());
	    	userCardJournal.setJournalDate(new Date());
	    
	    	if (("4".equals(commont)))  {
	    		userCardJournal.setJournalDesc("送药服务,收费");
			}else{
				userCardJournal.setJournalDesc("挂号服务,收费");
			}
	    	
	    	//userCardJournal.setGoodsid(record.getGoodsid().intValue());
	    	userCardJournal.setVoucherid(Long.valueOf(record.getRegisterid()));
	    	userCardJournal.setComment(commont);
	    	//记录日志
	    	userCardJournalDao.insert(userCardJournal);
	    	
	    	//日志处理  钱包支付  额度
	    	record.setPayTypeId(Constant.CONSTANTS_PAYMENT_WALLET);
	    	record.setRegisterTotal(userCardList.getTemp());
	    	delayUpdateUserAccountJournal(record, record.getUserid(),"");
		}
		return order;
	}
	
	
	
	
	
	/**
	 * 卡余额不足从钱包中支付
	 */
	@Override
	public RegisterOrderExample updateOrder4WalletAndCardPaymentDoc(RegisterOrder record,UserCardList userCardList,String commont,BigDecimal left ){
		
		
		//卡余额不足从钱包中支付
		RegisterOrderExample order = new RegisterOrderExample();
		
		UserAccountLedger accountLedger = userAccountLedgerDao.selectByUserId(record.getUserid());
		
		if (null ==accountLedger||accountLedger.getBalanceTotal().compareTo(left)<0) {
			//余额不足
			order.setUpdateNum(-2);
			return order;
		}else{
			
			accountLedger.setBalanceTotal(accountLedger.getBalanceTotal().subtract(left));
			userAccountLedgerDao.updateBalance(accountLedger);
		}
		
		
		int result=-1;
		//更新主订单数据
	    result= registerOrderDao.updateOrderSelective(record);
	    //更新card账户数据
	    userCardListDao.updateByPrimaryKeySelective(userCardList);
		//更新成功数目
		order.setUpdateNum(result);
		
		if (result==1) {
		    //插入订单日志
			
			delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_2,record.getUserid());
 
	    	//处理更新卡支付日记账表
			UserCardJournal userCardJournal = new UserCardJournal();
			userCardJournal.setJournalAmount(userCardList.getTemp().multiply(new BigDecimal(-1)));
	    	userCardJournal.setCardid(userCardList.getCardid());
	    	userCardJournal.setOwnerid(userCardList.getOwnerid());
	    	userCardJournal.setCarditemid((short)userCardList.getCardtypeid().intValue());
	    	userCardJournal.setJournalDate(new Date());
	    	userCardJournal.setJournalDesc(record.getOrderTypeDesc());
	    	userCardJournal.setVoucherid(Long.valueOf(record.getRegisterid()));
	    	userCardJournal.setComment(commont);
	       	if (("4".equals(commont)))  {
	    		userCardJournal.setJournalDesc("送药服务,收费");
			}else{
				userCardJournal.setJournalDesc("挂号服务,收费");
			}
	    	
			
	    	//记录日志
	    	userCardJournalDao.insert(userCardJournal);
	    	//待缺
	    	 record.setPayTypeId(Constant.CONSTANTS_PAYMENT_WALLET);
	    	delayUpdateUserAccountJournal(record, record.getUserid(),"");
		 
		}
		return order;
	}
	
	

	/**
	 * 卡余额不足从钱包中支付
	 */
	@Override
	public RegisterOrderExample updateOrder4WalletAndCardPaymentDoc(RegisterOrder record, List<UserCardList> userCardList,String comment,BigDecimal left) {
		
		
		RegisterOrderExample order = new RegisterOrderExample();
		
		UserAccountLedger accountLedger = userAccountLedgerDao.selectByUserId(record.getUserid());
		
		if (null ==accountLedger||accountLedger.getBalanceTotal().compareTo(left)<0) {
			//余额不足
			order.setUpdateNum(-2);
			return order;
		}else{
			
			accountLedger.setBalanceTotal(accountLedger.getBalanceTotal().subtract(left));
			
			userAccountLedgerDao.updateBalance(accountLedger);
		}
		
		int result = -1;
		// 更新主订单数据
		result = registerOrderDao.updateOrderSelective(record);
		// 更新card账户数据
		String[] amounts = record.getCardJournalAmount().split(",");

		List<UserCardJournal> userCardJournalList = new ArrayList<UserCardJournal>();
		for (int i = 0; i < userCardList.size(); i++) {

			UserCardList usercCard = userCardList.get(i);
			// 处理更新卡支付日记账表
			UserCardJournal userCardJournal = new UserCardJournal();
			userCardJournal.setJournalAmount(usercCard.getTemp().multiply(new BigDecimal(-1)));
			userCardJournal.setCardid(usercCard.getCardid());
			userCardJournal.setOwnerid(usercCard.getOwnerid());
			userCardJournal.setCarditemid((short) usercCard.getCardtypeid().intValue());
			userCardJournal.setJournalDate(new Date());
			userCardJournal.setJournalDesc(record.getOrderTypeDesc());
			userCardJournal.setVoucherid(Long.valueOf(record.getRegisterid()));
			userCardJournal.setComment(comment);
			// 记录日志
			record.setPayTypeId(Constant.CONSTANTS_PAYMENT_WALLET);
			userCardJournalList.add(userCardJournal);
		}
		userCardListDao.updateByPrimaryKeySelectiveBatch(userCardList);
		userCardJournalDao.insertBatch(userCardJournalList);

		// 更新成功数目
		order.setUpdateNum(result);
		// 记录订单动作
		delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_2, record.getUserid());
		// 记录用户账单
		delayUpdateUserAccountJournal(record, record.getUserid(), "");

		return order;

	}
	
	

	/**
	 * record:订单信息
	 * userCardList：用户卡信息
	 * scheduleInfo：预约信息
	 * 
	 */
	@Override
	public RegisterOrderExample updateOrder4CardPaymentDoc(RegisterOrder record, List<UserCardList> userCardList,String comment ) {
	
		RegisterOrderExample order = new RegisterOrderExample();
			int result=-1;
		//更新主订单数据
	    result= registerOrderDao.updateOrderSelective(record);
	    //更新card账户数据
	    String[] amounts = record.getCardJournalAmount().split(",");
	    List<UserCardJournal> userCardJournalList = new ArrayList<UserCardJournal>(); 
	    BigDecimal total = new BigDecimal(0);
	    for (int i = 0; i < userCardList.size(); i++) {
	    	
	    	UserCardList usercCard = userCardList.get(i);
	    	//处理更新卡支付日记账表
			UserCardJournal userCardJournal = new UserCardJournal();
			userCardJournal.setJournalAmount(usercCard.getTemp().multiply(new BigDecimal(-1)));
			total = total.add(new BigDecimal(amounts[i]));
	    	userCardJournal.setCardid(usercCard.getCardid());
	    	userCardJournal.setOwnerid(usercCard.getOwnerid());
	    	userCardJournal.setCarditemid((short)usercCard.getCardtypeid().intValue());
	    	userCardJournal.setJournalDate(new Date());
	    	userCardJournal.setJournalDesc(record.getOrderTypeDesc());
	    	userCardJournal.setVoucherid(Long.valueOf(record.getRegisterid()));
	    	if (("4".equals(comment)))  {
	    		userCardJournal.setJournalDesc("送药服务,收费");
			}else{
				userCardJournal.setJournalDesc("挂号服务,收费");
			}
	    	userCardJournal.setComment(comment);
	    	//记录日志
	    	userCardJournalList.add(userCardJournal);
		}
	    userCardListDao.updateByPrimaryKeySelectiveBatch(userCardList);
	    userCardJournalDao.insertBatch(userCardJournalList);
	
		//更新成功数目
		order.setUpdateNum(result);
		//记录订单动作
		delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_2,record.getUserid());
		//记录用户账单
		record.setPayTypeId(Constant.CONSTANTS_PAYMENT_WALLET);
		record.setRegisterTotal(total);
		delayUpdateUserAccountJournal(record, record.getUserid(),"");
    	
		return order;
	
	}
	
	
	
	/**
	 * record:订单信息
	 * userCardList：用户卡信息
	 * scheduleInfo：预约信息
	 * 
	 */
	@Override
	public RegisterOrderExample updateOrder4CardPayment(RegisterOrder record, List<UserCardList> userCardList,String comment ) {
	
		RegisterOrderExample order = new RegisterOrderExample();
			int result=-1;
		//更新主订单数据
	    result= registerOrderDao.updateOrderSelective(record);
	    //更新card账户数据
	    String[] amounts = record.getCardJournalAmount().split(",");
	    
	    List<UserCardJournal> userCardJournalList = new ArrayList<UserCardJournal>(); 
	    for (int i = 0; i < userCardList.size(); i++) {
	    	
	    	UserCardList usercCard = userCardList.get(i);
	    	//处理更新卡支付日记账表
			UserCardJournal userCardJournal = new UserCardJournal();
			userCardJournal.setJournalAmount(new BigDecimal(amounts[i]).multiply(new BigDecimal(-1)));
	    	userCardJournal.setCardid(usercCard.getCardid());
	    	userCardJournal.setOwnerid(usercCard.getOwnerid());
	    	userCardJournal.setCarditemid((short)usercCard.getCardtypeid().intValue());
	    	userCardJournal.setJournalDate(new Date());
	    	userCardJournal.setJournalDesc(record.getOrderTypeDesc());
	    	userCardJournal.setGoodsid(record.getGoodsid().intValue());
	    	userCardJournal.setVoucherid(Long.valueOf(record.getRegisterid()));
	    	userCardJournal.setComment(comment);
	    	//记录日志
	    	userCardJournalList.add(userCardJournal);
		}
	    userCardListDao.updateByPrimaryKeySelectiveBatch(userCardList);
	    userCardJournalDao.insertBatch(userCardJournalList);
	    
	    //预约类咨询
    	if (record.getRegistertypeid().intValue()!=Constant.CONSTANTS_ORDER_TYPE_ID_1.intValue()) {
    		RegisterOrderZSchedule schedule = new RegisterOrderZSchedule();
			schedule.setRegisterid(record.getRegisterid());
			schedule.setStatus(Constant.CONSTANTS_IS_USERED);
			registerOrderZScheduleDao.updateByPrimaryKeySelective(schedule);
		}
		//更新成功数目
		order.setUpdateNum(result);
		//记录订单动作
		delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_2,record.getUserid());
		//记录用户账单
		delayUpdateUserAccountJournal(record, record.getUserid(),"");
		
		return order;
	
	}
	
	/**
	 * 卡余额不足从钱包中支付
	 */
	@Override
	public RegisterOrderExample updateOrder4WalletAndCardPayment(RegisterOrder record,UserCardList userCardList,String commont,BigDecimal left ){
		
		
		//卡余额不足从钱包中支付
		RegisterOrderExample order = new RegisterOrderExample();
		
		UserAccountLedger accountLedger = userAccountLedgerDao.selectByUserId(record.getUserid());
		
		if (null ==accountLedger||accountLedger.getBalanceTotal().compareTo(left)<0) {
			//余额不足
			order.setUpdateNum(-2);
			return order;
		}else{
			
			accountLedger.setBalanceTotal(accountLedger.getBalanceTotal().subtract(left));
			
			userAccountLedgerDao.updateBalance(accountLedger);
		}
		
		
		int result=-1;
		//更新主订单数据
	    result= registerOrderDao.updateOrderSelective(record);
	    //更新card账户数据
	    userCardListDao.updateByPrimaryKeySelective(userCardList);
		//更新成功数目
		order.setUpdateNum(result);
		
		if (result==1) {
		    //插入订单日志
			
			delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_2,record.getUserid());
 
	    	//处理更新卡支付日记账表
			UserCardJournal userCardJournal = new UserCardJournal();
			userCardJournal.setJournalAmount(new BigDecimal(record.getCardJournalAmount()).multiply(new BigDecimal(-1)));
	    	userCardJournal.setCardid(userCardList.getCardid());
	    	userCardJournal.setOwnerid(userCardList.getOwnerid());
	    	userCardJournal.setCarditemid((short)userCardList.getCardtypeid().intValue());
	    	userCardJournal.setJournalDate(new Date());
	    	userCardJournal.setJournalDesc(record.getOrderTypeDesc());
	    	userCardJournal.setGoodsid(record.getGoodsid().intValue());
	    	userCardJournal.setVoucherid(Long.valueOf(record.getRegisterid()));
	    	userCardJournal.setComment(commont);
			
	    	//预约类咨询
	    	if (record.getRegistertypeid().intValue()!=Constant.CONSTANTS_ORDER_TYPE_ID_1.intValue()) {
				
				RegisterOrderZSchedule schedule = new RegisterOrderZSchedule();
				schedule.setRegisterid(record.getRegisterid());
				schedule.setStatus(Constant.CONSTANTS_IS_USERED);
				registerOrderZScheduleDao.updateByPrimaryKeySelective(schedule);
			}
	    	//记录日志
	    	userCardJournalDao.insert(userCardJournal);
	    	delayUpdateUserAccountJournal(record, record.getUserid(),"");
		 
		}
		return order;
	}
	
	
	/**
	 * 卡余额不足从钱包中支付
	 */
	@Override
	public RegisterOrderExample updateOrder4WalletAndCardPayment(RegisterOrder record, List<UserCardList> userCardList,String comment,BigDecimal left) {
		
		
		RegisterOrderExample order = new RegisterOrderExample();
		
		UserAccountLedger accountLedger = userAccountLedgerDao.selectByUserId(record.getUserid());
		
		if (null ==accountLedger||accountLedger.getBalanceTotal().compareTo(left)<0) {
			//余额不足
			order.setUpdateNum(-2);
			return order;
		}else{
			
			accountLedger.setBalanceTotal(accountLedger.getBalanceTotal().subtract(left));
			
			userAccountLedgerDao.updateBalance(accountLedger);
		}
		
		int result = -1;
		// 更新主订单数据
		result = registerOrderDao.updateOrderSelective(record);
		// 更新card账户数据
		String[] amounts = record.getCardJournalAmount().split(",");

		List<UserCardJournal> userCardJournalList = new ArrayList<UserCardJournal>();
		for (int i = 0; i < userCardList.size(); i++) {

			UserCardList usercCard = userCardList.get(i);
			// 处理更新卡支付日记账表
			UserCardJournal userCardJournal = new UserCardJournal();
			userCardJournal.setJournalAmount(new BigDecimal(amounts[i]).multiply(new BigDecimal(-1)));
			userCardJournal.setCardid(usercCard.getCardid());
			userCardJournal.setOwnerid(usercCard.getOwnerid());
			userCardJournal.setCarditemid((short) usercCard.getCardtypeid().intValue());
			userCardJournal.setJournalDate(new Date());
			userCardJournal.setJournalDesc(record.getOrderTypeDesc());
			userCardJournal.setGoodsid(record.getGoodsid().intValue());
			userCardJournal.setVoucherid(Long.valueOf(record.getRegisterid()));
			userCardJournal.setComment(comment);
			// 记录日志
			userCardJournalList.add(userCardJournal);
		}
		userCardListDao.updateByPrimaryKeySelectiveBatch(userCardList);
		userCardJournalDao.insertBatch(userCardJournalList);

		// 预约类咨询
		if (record.getRegistertypeid().intValue() != Constant.CONSTANTS_ORDER_TYPE_ID_1.intValue()) {
			RegisterOrderZSchedule schedule = new RegisterOrderZSchedule();
			schedule.setRegisterid(record.getRegisterid());
			schedule.setStatus(Constant.CONSTANTS_IS_USERED);
			registerOrderZScheduleDao.updateByPrimaryKeySelective(schedule);
		}
		// 更新成功数目
		order.setUpdateNum(result);
		// 记录订单动作
		delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_2, record.getUserid());
		// 记录用户账单
		delayUpdateUserAccountJournal(record, record.getUserid(), "");

		return order;

	}
	
	/**
	 * 钱包支付
	 */
	public RegisterOrderExample updateOrder4WalletPayment(RegisterOrder record ) 
	{
		int result=-1;
		RegisterOrderExample order = new RegisterOrderExample();
		
		UserAccountLedger accountLedger = userAccountLedgerDao.selectByUserId(record.getUserid());
		
		if (null ==accountLedger||accountLedger.getBalanceTotal().compareTo(record.getRegisterTotal())<0) {
			//余额不足
			order.setUpdateNum(-2);
			return order;
		}else{
			
			accountLedger.setBalanceTotal(accountLedger.getBalanceTotal().subtract(record.getRegisterTotal()));
			
			userAccountLedgerDao.updateBalance(accountLedger);
		}
		
		//更新主订单数据
	    result= registerOrderDao.updateOrderSelective(record);
	    
	    delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_2,record.getUserid());
		
		delayUpdateUserAccountJournal(record, record.getUserid(),"");
		
		order.setUpdateNum(result);
		return order;
	}
	 
	
	/**
	 * 延时处理更新doc表
	 */
	private void delayUpdateDocAccountJournal(RegisterOrder  orderInfoTemp,long userId, UserAccountLedger accountLedger) {

			// 查看用户表相关信息
			//Long docId = userId;
			UserLIST userLIST = userLISTDao.selectByUserId(userId);

			// 账单日志表
			//日记账记录
			UserAccountJournal accountJournal = new UserAccountJournal();
			accountJournal.setJournalDesc(orderInfoTemp.getUserName()+ orderInfoTemp.getOrderTypeDesc());
			accountJournal.setVoucherName(Constant.CONSTANTS_VOUCHERNAME_1);
			
			accountJournal.setAcctpageid(accountLedger.getAcctpageid());
			accountJournal.setAccountid(userId);
			accountJournal.setAccountIdno(userLIST.getUserNo());
			accountJournal.setAccountName(userLIST.getUserName());
			accountJournal.setVoucherid(orderInfoTemp.getRegisterid().toString());
			accountJournal.setVoucherIdno(orderInfoTemp.getRegisterNo());
			//accountJournal.setJournalDesc(orderInfoTemp.getUserName()+ orderInfoTemp.getOrderTypeDesc());
			//accountJournal.setVoucherName(Constant.CONSTANTS_VOUCHERNAME_1);
			accountJournal.setJournalTotal(orderInfoTemp.getRegisterPayoffTotal());
			accountJournal.setCreateUserid(userId);
			accountJournal.setUpdateUserid(userId);
			accountJournal.setVoucherDate(orderInfoTemp.getRegisterDate());
			accountJournal.setVouchertypeid(Integer.valueOf("1"+ orderInfoTemp.getRegistertypeid()));

			// 新的账单表
			if (StringUtils.isEmpty(accountLedger.getAccountIdno())) {
				accountLedger.setAccountIdno(userLIST.getUserNo());
				accountLedger.setAccountName(userLIST.getUserName());
				accountLedger.setCreateUserid(userId);
				accountLedger.setUpdateUserid(userId);
				userAccountLedgerDao.updatAccountLedgerByUserIdSelective(accountLedger);
			}
			userAccountJournalDao.insert(accountJournal);
		}
	
	
	/**
	 * 延时处理更新user表
	 * 支付回调调用
	 * accountJournal 用户记录
	 */
	private void delayUpdateUserAccountJournal(UserAccountJournal accountJournal,RegisterOrder  orderInfoTemp,
			long userId, UserAccountLedger accountLedger) {

			// 查看用户表相关信息
			//Long docId = userId;
			UserLIST userLIST = userLISTDao.selectByUserId(userId);

			// 账单日志表
			//日记账记录
			//accountJournal.setAcctpageid(accountLedger.getAcctpageid());
			accountJournal.setAccountid(userId);
			accountJournal.setAccountIdno(userLIST.getUserNo());
			accountJournal.setAccountName(userLIST.getUserName());
			accountJournal.setVoucherid(orderInfoTemp.getRegisterid().toString());
			accountJournal.setVoucherIdno(orderInfoTemp.getRegisterNo());
			//accountJournal.setJournalDesc(orderInfoTemp.getUserName()+ orderInfoTemp.getOrderTypeDesc());
			//accountJournal.setVoucherName(Constant.CONSTANTS_VOUCHERNAME_1);
			accountJournal.setJournalTotal(orderInfoTemp.getRegisterTotal());
			//accountJournal.setJournalTotal(orderInfoTemp.getRegisterPayoffTotal());
			accountJournal.setCreateUserid(userId);
			accountJournal.setUpdateUserid(userId);
			accountJournal.setVoucherDate(orderInfoTemp.getRegisterDate());
			accountJournal.setVouchertypeid(Integer.valueOf("1"+ orderInfoTemp.getRegistertypeid()));

			// 新的账单表
			if (StringUtils.isEmpty(accountLedger.getAccountIdno())) {
				accountLedger.setAccountIdno(userLIST.getUserNo());
				accountLedger.setAccountName(userLIST.getUserName());
				accountLedger.setCreateUserid(userId);
				accountLedger.setUpdateUserid(userId);
				userAccountLedgerDao.updatAccountLedgerByUserIdSelective(accountLedger);
			}
			userAccountJournalDao.insert(accountJournal);
		}
	
	/**
	 * 延时处理更新user表
	 * 支付回调调用
	 * accountJournal 用户记录
	 */
	private void delayUpdateUserAccountJournal(RegisterOrder  record,long userId,String out_trade_no ) {

			UserAccountJournal accountJournal = new UserAccountJournal();
			//支付成功
			if (record.getPayTypeId().shortValue()==Constant.CONSTANTS_PAYMENT_WEIXIN) {
				accountJournal.setJournalDesc(Constant.CONSTANTS_VOUCHERNAME_2 +"订单号"+out_trade_no);
				accountJournal.setVoucherName(Constant.CONSTANTS_VOUCHERNAME_2);
				accountJournal.setJournalTotal(record.getRegisterTotal());
			
			}else if(record.getPayTypeId().shortValue()==Constant.CONSTANTS_PAYMENT_ALIPAY){
				accountJournal.setJournalDesc(Constant.CONSTANTS_VOUCHERNAME_4 +"订单号"+out_trade_no);
				accountJournal.setVoucherName(Constant.CONSTANTS_VOUCHERNAME_4);
				accountJournal.setJournalTotal(record.getRegisterTotal());
			}else if (record.getPayTypeId().shortValue()==Constant.CONSTANTS_PAYMENT_WALLET) {
				
				accountJournal.setJournalDesc(Constant.CONSTANTS_VOUCHERNAME_9);
				accountJournal.setVoucherName(Constant.CONSTANTS_VOUCHERNAME_9);
				accountJournal.setJournalTotal(record.getRegisterTotal());
				accountJournal.setPeriodid(Integer.valueOf(Constant.CONSTANTS_PAYMENT_WALLET));
			}else if(record.getPayTypeId().shortValue()==Constant.CONSTANTS_PAYMENT_SERVICE_CARD){
				accountJournal.setJournalDesc(Constant.CONSTANTS_VOUCHERNAME_7 );
				accountJournal.setVoucherName(Constant.CONSTANTS_VOUCHERNAME_7);
				accountJournal.setJournalTotal(new BigDecimal(0));
			}
			accountJournal.setSourceid(Constant.CONSTANTS_PAY_ACTION_ID_11);
			
			//商户订单号 作为备注
			accountJournal.setComment(out_trade_no);
			// 查看用户表相关信息
			//Long docId = userId;
			UserLIST userLIST = userLISTDao.selectByUserId(userId);

			// 账单日志表
			//日记账记录
			accountJournal.setAccountid(userId);
			accountJournal.setAccountIdno(userLIST.getUserNo());
			accountJournal.setAccountName(userLIST.getUserName());
			accountJournal.setVoucherid(record.getRegisterid().toString());
			accountJournal.setVoucherIdno(record.getRegisterNo());
			
			accountJournal.setCreateUserid(userId);
			accountJournal.setUpdateUserid(userId);
			accountJournal.setVoucherDate(new Date());
			accountJournal.setVouchertypeid(Integer.valueOf("1"+ record.getRegistertypeid()));
			
			userAccountJournalDao.insert(accountJournal);
		}
	
	@Override
	public int processRunStatus1OrderTimeout(List<RegisterOrder> registerOrderTempList,String timeDefine) {
		
		//系统超时处理
		Long systemUserId=PropertiesUtil.getLong("defalutUser",2);
		for(RegisterOrder order:registerOrderTempList)
		{
			try{
			Date updateDate=order.getCreateDate();
			Date currDate=DateUtils.now();
			double gapHour=Double.valueOf(timeDefine);
			if(DateUtils.judgmentDate(updateDate, currDate,gapHour))
			{
				continue;
			}
			
			
			//判断订单更新时间是否已过指定时间
			
			RegisterOrder temp= new RegisterOrder();
			
			temp.setUpdateDate(new Date());
			temp.setUpdateUserid(order.getUserid());
			temp.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_6);
			temp.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_6);
			temp.setRegisterid(order.getRegisterid());
			
			//更新订单状态为关闭
			registerOrderDao.updateOrderState4Timeout(temp);
			
			//日志
			//这里的userid应该用一个系统公用的用户
			delayOrderActionRecord(order.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_10,systemUserId);
			}catch (Exception e) {
				// TODO: handle exception
			}
		}
		return 0;
	}

	@Override
	public int processRunStatus7OrderTimeout(List<RegisterOrder> registerOrderTempList,String timeDefine) {
		
		//先修改订单表状态
		//多种情况
		//等待支付的订单如果超过24小时，则直接转状态为关闭，写状态变化日志
		//registerOrderDao.updateOrderSelective(record);
		
		
		//等待支付的订单如果超过24小时，则直接转状态为关闭，写状态变化日志 ，订单状态变化为：1-->6
		//待评价订单如果超过7天，则直接转状态为完成，将钱打到医生账户，写状态变化日志，写账户变化日志。订单状态变化为： 4-->5
		//更新账户表
		
		//RegisterOrderAction registerOrderActionRecord =new RegisterOrderAction();
		
		//写入订单日志表状态变化情况
		//registerOrderActionDao.insert(registerOrderActionRecord);
		return 0;
	}

	 

	@Override
	public int updateOrder4Confirm(RegisterOrder record) {
		int result=-1; 
		result= registerOrderDao.updateOrderSelective(record);
		
		delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_RUNSTATUS_ID_5,record.getAccepterid());
		
		
		return result;
	}

	@Override
	public int updateOrder4Cancel(RegisterOrder record) {
	
		//EPayCashPayment ePayCashPayment = ePayCashPaymentDao.selectByOrderId(record.getRegisterid());
	
		int result=-1; 
		result= registerOrderDao.updateOrderSelective(record);
		
		 //预约类订单
	    //确认号源
	    if (record.getRegistertypeid().intValue()==Constant.CONSTANTS_ORDER_TYPE_ID_3.intValue()) {
    		RegisterOrderZSchedule schedule = new RegisterOrderZSchedule();
			schedule.setRegisterid(record.getRegisterid());
			schedule.setStatus(Constant.CONSTANTS_NOT_USERED);
			registerOrderZScheduleDao.updateByPrimaryKeySelective(schedule);
	    }
		
		delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_8,record.getUserid());
		
		return result;
	}

	@Override
	public int updateOrder4Delete(RegisterOrder record) {
		int result=-1; 
		result= registerOrderDao.updateOrderSelective(record);
		return result;
	}

	/**
	 * @param record订单信息
	 * @param userAccountLedger 用户账户信息
	 * @param type 支付方式
	 * @param out_trade_no 平台订单号   
	 */
	@Override
	public RegisterOrderExample updateOrder4Payment(RegisterOrder  record,UserAccountLedger userAccountLedger,int type,String out_trade_no) {
 
			  RegisterOrderExample order = new RegisterOrderExample();
			  int result=-1;
				  
			    result= registerOrderDao.updateOrderSelective(record);
			    delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_2,record.getUserid());
			    
			    //这里先注释掉，现在只是支付流程，不涉及钱的转移，要等订单完成（用户主动发起结束订单和订单自动超时时），钱才会进到医生账户
			    
			    //预约类订单
			    //确认号源
			    if (record.getRegistertypeid()!=Constant.CONSTANTS_ORDER_TYPE_ID_1) {
		    		RegisterOrderZSchedule schedule = new RegisterOrderZSchedule();
					schedule.setRegisterid(record.getRegisterid());
					schedule.setStatus(Constant.CONSTANTS_IS_USERED);
					registerOrderZScheduleDao.updateByPrimaryKeySelective(schedule);
			    }
			    
				//更新成功数目
				order.setUpdateNum(result);
				
				delayUpdateUserAccountJournal(record, record.getUserid(),out_trade_no);
				
				return order;
	 
	}
	@Override
	public int processRunStatus2OrderTimeout(
			List<RegisterOrder> registerOrderTempList,String timeDefine)  {
		
		//系统超时处理
		Long systemUserId=PropertiesUtil.getLong("defalutUser",2);
		
		IEPayCashPaymentService ePayCashPaymentService =	SpringContextUtil.getBean("ePayCashPaymentService");
		IWXPayService wXPayService =SpringContextUtil.getBean("wXPayService");
		IAlipayService alipayService =	SpringContextUtil.getBean("alipayService");
		IUserCardListService userCardListService = 	SpringContextUtil.getBean("userCardListService");
		
		
		
		for(RegisterOrder order:registerOrderTempList)
		{
			try{
			Date updateDate=order.getCreateDate();
			Date currDate=DateUtils.now();
			double gapHour=Double.valueOf(timeDefine);
			if(DateUtils.judgmentDate(updateDate, currDate,gapHour))
			{
				continue;
			}
			
			EPayCashPayment ePayCashPayment = null;

			//先做退款操作
			if(order.getOrderfeetypeid().intValue()!=Constant.CONSTANTS_ORDER_FREE_ID_0.intValue()){
				short payTypeId = order.getPayTypeId();
				Long orderId = order.getRegisterid();
				//微信退款
				if(payTypeId==Constant.CONSTANTS_PAYMENT_WEIXIN)	{
					
					List<EPayCashPayment> ePayCashPaymentList = ePayCashPaymentService.selectByOrderId(orderId);
					if (ePayCashPaymentList.size()==1) {
						
							ePayCashPayment = ePayCashPaymentList.get(0);
							int fee = ePayCashPayment.getPaycashTotal().multiply(new BigDecimal(100)).intValue();
							RefundReqData refundReqData = new RefundReqData(
									ePayCashPayment.getBankCashIdno(), ePayCashPayment.getPaycashIdno(), null,
									ePayCashPayment.getPaycashIdno(),fee,fee, null, null);
							try {
								RefundResData refundResData = wXPayService.refund(refundReqData);
								
								String resultCode = refundResData.getResult_code();
								
								if (StringUtils.isNotBlank(resultCode)&&resultCode.equals("SUCCESS")) {
									
								}else{
									continue;
								}
								
								
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							//更新回调日志表
							EPayCashPayment ePayCashPaymentForUpdate = new EPayCashPayment();
							ePayCashPaymentForUpdate.setPaycashid(ePayCashPayment.getPaycashid());
							ePayCashPaymentForUpdate.setPaycashIdno(ePayCashPayment.getPaycashIdno()+"R");
							ePayCashPaymentForUpdate.setPaycashSign(Constant.CONSTANTS_IS_PAYMENT_CANCEL);
							ePayCashPaymentService.updateByPayCashIDSelective(ePayCashPayment,ePayCashPaymentForUpdate,order);
					}
					
				//支付宝退款	
				}else if (payTypeId==Constant.CONSTANTS_PAYMENT_ALIPAY) {
								
					
					
					List<EPayCashPayment> ePayCashPaymentList = ePayCashPaymentService.selectByOrderId(orderId);
					if (ePayCashPaymentList.size()==1) {
						
						ePayCashPayment =  ePayCashPaymentList.get(0);
						try {
							alipayService.refund(ePayCashPayment.getPaycashIdno(), ePayCashPayment.getBankCashIdno(), 
												 String.valueOf(ePayCashPayment.getPaycashTotal().setScale(2)),
												 null, null, null, null, null);
						} catch (AlipayApiException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						//更新回调日志表
						EPayCashPayment ePayCashPaymentForUpdate = new EPayCashPayment();
						ePayCashPaymentForUpdate.setPaycashid(ePayCashPayment.getPaycashid());
						ePayCashPaymentForUpdate.setPaycashIdno(ePayCashPayment.getPaycashIdno()+"R");
						ePayCashPaymentForUpdate.setPaycashSign(Constant.CONSTANTS_IS_PAYMENT_CANCEL);
						ePayCashPaymentService.updateByPayCashIDSelective(ePayCashPayment,ePayCashPaymentForUpdate,order);					
					}
					
				//健康卡退款	
				}else if (payTypeId==Constant.CONSTANTS_PAYMENT_SERVICE_CARD) {	
					
					//图文咨询
					if (order.getRegistertypeid()==Constant.CONSTANTS_ORDER_TYPE_ID_1) {
						 
						long cardId=Long.valueOf(order.getCardID());
						//查到具体是哪张卡里扣减的
						UserCardList  userCardList =userCardListService.selectByCardId(cardId);
						
						if(null!=userCardList){
						
						userCardList.setLefttime01(userCardList.getLefttime01().add(new BigDecimal(1)));
						this.updateOrder4CardRefound(order, userCardList);
						}
					}
					else
					{
						String[] cardIds=order.getCardID().split(",");
						//多条批处理
						if (cardIds.length==1) {
							//查到具体是哪张卡里扣减的
							UserCardList  userCardList =userCardListService.selectByCardId(Long.valueOf(order.getCardID()));
							
							if(null!=userCardList){
							
								userCardList.setLefttime03(userCardList.getLefttime03().add(new BigDecimal(order.getCardJournalAmount())));
								this.updateOrder4CardRefound(order, userCardList);
							}
						}else{
							
							String[] cardLeftTime=order.getCardJournalAmount().split(",");
							
							UserCardListExt example = new UserCardListExt();
							example.setOwnerid(order.getUserid());
							//查询所有的cardList
							List<UserCardList> userCardLists =userCardListService.selectUserCardLists(example);
							//需要更新的表
							List<UserCardList> userCardListsForUpdate = new ArrayList<UserCardList>();
							Map<String,UserCardList> map = new HashMap<String, UserCardList>();
							for (int i = 0; i < userCardLists.size(); i++) {
								UserCardList card = userCardLists.get(i);
								map.put(String.valueOf(card.getCardid()), card);
							}
							
							for (int i = 0; i < cardIds.length; i++) {
								//查到具体是哪张卡里扣减的
								UserCardList  userCardList =map.get(cardIds[i]);
								 //剩余时间
								userCardList.setLefttime03(userCardList.getLefttime03().add(new BigDecimal(cardLeftTime[i])));
								userCardListsForUpdate.add(userCardList);
							}
							
							this.updateOrder4CardRefound(order, userCardListsForUpdate);
						}
					}
				}else if(payTypeId==Constant.CONSTANTS_PAYMENT_WALLET){
					UserAccountLedger accountLedger = userAccountLedgerDao.selectByUserId(order.getUserid());
					
					accountLedger.setBalanceTotal(accountLedger.getBalanceTotal().add(order.getRegisterTotal()));
						
					userAccountLedgerDao.updateBalance(accountLedger);
				    
				}
			}
			RegisterOrder temp= new RegisterOrder();
			
			temp.setUpdateDate(new Date());
			temp.setUpdateUserid(order.getUserid());
			temp.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_6);
			temp.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_6);
			temp.setRegisterid(order.getRegisterid());
			temp.setUpdateUserid(systemUserId);
			
			//更新订单状态为关闭
			registerOrderDao.updateOrderSelective(temp);
			
			//预约类订单
		    //确认号源
		    if (temp.getRegistertypeid()!=Constant.CONSTANTS_ORDER_TYPE_ID_1) {
	    		RegisterOrderZSchedule schedule = new RegisterOrderZSchedule();
				schedule.setRegisterid(temp.getRegisterid());
				schedule.setStatus(Constant.CONSTANTS_IS_USERED);
				registerOrderZScheduleDao.updateByPrimaryKeySelective(schedule);
		    }
			
			//日志
			delayOrderActionRecord(order.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_11,systemUserId);
			}catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		return 0;
	}

	@Override
	public int processRunStatus3OrderTimeout(
			List<RegisterOrder> registerOrderTempList,String timeDefine) {

		//系统超时处理
		Long systemUserId=PropertiesUtil.getLong("defalutUser",2);
		for(RegisterOrder order:registerOrderTempList)
		{
			try{
				Date updateDate=order.getUpdateDate();
				Date currDate=DateUtils.now();
				double gapHour=Double.valueOf(timeDefine);
				if(DateUtils.judgmentDate(updateDate, currDate,gapHour))
				{
					continue;
				}
				
				long docId=order.getAccepterid();
				
				BigDecimal orderPayoffTotal=order.getRegisterPayoffTotal();
				
				//医生的账户
				UserAccountLedger accountLedger = new UserAccountLedger();
		  
				//医生账户表
				//关闭时，医生账户里获得相应的订单金额
				//分类账户更新数据
				//查询到当前医生的账户
				accountLedger = userAccountLedgerDao.selectByUserId(docId);
	
				// 查看用医生相关信息
		 
				UserLIST userLIST = userLISTDao.selectByUserId(docId);
				
				//如果医生应得到的为0 不做插入日志处理
				if (orderPayoffTotal.compareTo(new BigDecimal(0))>0) {
					//有账户则直接给账户增加订单金额
					if (null!=accountLedger&&accountLedger.getAcctpageid().intValue()!=0) {
					 
						BigDecimal balanceTotal=(BigDecimal) (accountLedger.getBalanceTotal()==null?new BigDecimal(0):accountLedger.getBalanceTotal());
						
						//医生获得的补偿累加
						accountLedger.setBalanceTotal(balanceTotal.add(orderPayoffTotal));
						accountLedger.setAccountIdno(userLIST.getUserNo());
						accountLedger.setAccountName(userLIST.getUserName());
						accountLedger.setCreateUserid(docId);
						accountLedger.setUpdateUserid(docId);
						
					    userAccountLedgerDao.updateBalance(accountLedger);
					}
					else{
						//没有账户,要新创建一个账户
						accountLedger = new UserAccountLedger();
						accountLedger.setBalanceTotal(orderPayoffTotal);
						accountLedger.setAccountid(docId);
						accountLedger.setIsUsedFlag((short) 1);
						accountLedger.setAccountIdno(userLIST.getUserNo());
						accountLedger.setAccountName(userLIST.getUserName());
						accountLedger.setCreateUserid(docId);
						accountLedger.setUpdateUserid(docId);
						accountLedger.setColumnid(1);
					    userAccountLedgerDao.insertAccountLedger(accountLedger);
					}
				}
				
				order.setUpdateDate(new Date());
				
				//待评价剔除后修复
				order.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_4);
				order.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_4);
				order.setUpdateUserid(systemUserId);
				
				registerOrderDao.updateOrderSelective(order);
				
			    delayOrderActionRecord(order.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_12,systemUserId);
			    delayUpdateDocAccountJournal(order, docId, accountLedger);
			}
			catch (Exception e) {
			e.printStackTrace();
			}
		}
		
		return 0;
	}
	
	

	/**
	 * 
	 * 超时评价
	 * @param registerOrderTempList
	 * @param timeDefine
	 */
	@Override
	public int processRunStatus4OrderTimeout(
			List<RegisterOrder> registerOrderTempList,String timeDefine) {
		
		//系统超时处理
		Long systemUserId=PropertiesUtil.getLong("defalutUser",2);
		IRongService rongService  = SpringContextUtil.getBean("rongService");
		
		for(RegisterOrder order:registerOrderTempList)
		{
			try{
				Date updateDate=order.getUpdateDate();
				Date currDate=DateUtils.now();
				double gapHour=Double.valueOf(timeDefine);
				if(DateUtils.judgmentDate(updateDate, currDate,gapHour))
				{
					continue;
				}
				
				long docId=order.getAccepterid();
				
				order.setUpdateDate(new Date());
				
				//待评价剔除后修复
				order.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_5);
				order.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_5);
				
				order.setEvaluateFlag(Constant.CONSTANTS_ORDER_IS_COMMENT_1);
				order.setEvaluateDescribe(Constant.CONSTANTS_COMMON_EVALUATE);
				order.setEvaluateScore((short) 5);
				order.setUpdateUserid(systemUserId);
			
				registerOrderDao.updateOrderSelective(order);
				 
				String userId = String.valueOf(docId);
				String groupId = String.valueOf(order.getRegisterid());
				rongService.dismissGroup(userId, groupId);
				
				//评价不写入订单动作
			   // delayOrderActionRecord(order.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_13,systemUserId);
			}catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		return 0;
	}
	
	
	

	/**
	 * 根据付费方式得到账单类型
	 * @param orderDirect
	 * @param payTypeId
	 * @return
	 */
    public  String  getVoucherNameByPayTypeId(int orderDirect,short payTypeId)
    {
    
    	String voucherName="";
    	//正向
    	if(1==orderDirect)
    	{
    		if(payTypeId==Constant.CONSTANTS_PAYMENT_SERVICE_CARD)
        	{
        		voucherName=Constant.CONSTANTS_VOUCHERNAME_7;
        	}
        	else if(payTypeId==Constant.CONSTANTS_PAYMENT_WEIXIN)
        	{
        		voucherName=Constant.CONSTANTS_VOUCHERNAME_2;
        	}
        	else if(payTypeId==Constant.CONSTANTS_PAYMENT_ALIPAY)
        	{
        		voucherName=Constant.CONSTANTS_VOUCHERNAME_4;
        	}
        	else if(payTypeId==Constant.CONSTANTS_PAYMENT_BANK)
        	{
        		voucherName=Constant.CONSTANTS_VOUCHERNAME_1;
        	}
        	else if(payTypeId==Constant.CONSTANTS_PAYMENT_WALLET)
        	{
        		voucherName=Constant.CONSTANTS_VOUCHERNAME_9;
        	}
    	}
    	else
    	{//反向
    		
    		if(payTypeId==Constant.CONSTANTS_PAYMENT_SERVICE_CARD)
        	{
        		voucherName=Constant.CONSTANTS_VOUCHERNAME_8;
        	}
        	else if(payTypeId==Constant.CONSTANTS_PAYMENT_WEIXIN)
        	{
        		voucherName=Constant.CONSTANTS_VOUCHERNAME_3;
        	}
        	else if(payTypeId==Constant.CONSTANTS_PAYMENT_ALIPAY)
        	{
        		voucherName=Constant.CONSTANTS_VOUCHERNAME_5;
        	}
        	else if(payTypeId==Constant.CONSTANTS_PAYMENT_BANK)
        	{
        		voucherName=Constant.CONSTANTS_VOUCHERNAME_1;
        	}
        	else if(payTypeId==Constant.CONSTANTS_PAYMENT_WALLET)
        	{
        		voucherName=Constant.CONSTANTS_VOUCHERNAME_10;
        	}
    	}
    	
    	
    	return voucherName;
    }
    
    /**
     * 钱包退款
     */
	@Override
	public RegisterOrderExample updateOrder4WalletRefound(RegisterOrder record) {
		
		
		    RegisterOrderExample order = new RegisterOrderExample();
		    int result=-1;
		   
			UserAccountLedger accountLedger = userAccountLedgerDao.selectByUserId(record.getUserid());
			
			accountLedger.setBalanceTotal(accountLedger.getBalanceTotal().add(record.getRegisterTotal()));
			//result= registerOrderDao.updateOrderSelective(record);
			userAccountLedgerDao.updateBalance(accountLedger);
		    
		    delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_7,record.getUserid());
		    
	  		 UserAccountJournal accountJournal = new UserAccountJournal();
	  		 accountJournal.setJournalDesc(record.getOrderTypeDesc()+Constant.CONSTANTS_VOUCHERNAME_10);
			 accountJournal.setVoucherName(record.getOrderTypeDesc());
			
			 accountJournal.setAcctpageid(null);
			 accountJournal.setAccountid(record.getUserid());
			 accountJournal.setAccountIdno(record.getUserContact());
			 accountJournal.setAccountName(record.getUserName());
			 accountJournal.setVoucherid(record.getRegisterid().toString());
			 accountJournal.setVoucherIdno(record.getRegisterNo());
			 accountJournal.setJournalTotal(record.getRegisterTotal().multiply(new  BigDecimal(-1)));
			 accountJournal.setPeriodid(Integer.valueOf(Constant.CONSTANTS_PAYMENT_WALLET));
			 accountJournal.setCreateUserid(record.getUserid());
			 accountJournal.setUpdateUserid(record.getUserid());
			 accountJournal.setVoucherDate( new Date());
			 accountJournal.setVouchertypeid(Constant.CONSTANTS_PAY_ACTION_ID_31);
			 accountJournal.setComment("");
			 accountJournal.setSourceid(Constant.CONSTANTS_PAY_ACTION_ID_33);
			 
			 
			userAccountJournalDao.insert(accountJournal);
		     
			return order;
	}
	

	@Override
	public RegisterOrderExample updateOrder4CardRefound(RegisterOrder record,UserCardList userCardList) {
		  RegisterOrderExample order = new RegisterOrderExample();
		  int result=-1;
		  Date now = new Date();
	      userCardListDao.updateByPrimaryKeySelective(userCardList);
	      delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_7,record.getUserid());
	     
		  UserCardJournal userCardJournal = new UserCardJournal();
		  userCardJournal.setJournalAmount(new BigDecimal(record.getCardJournalAmount()));
    	  userCardJournal.setCardid(userCardList.getCardid());
    	  userCardJournal.setOwnerid(userCardList.getOwnerid());
    	  userCardJournal.setCarditemid((short)userCardList.getCardtypeid().intValue());
    	  userCardJournal.setJournalDate(now);
    	  userCardJournal.setJournalDesc(record.getOrderTypeDesc()+"退费");
    	  userCardJournal.setGoodsid(record.getGoodsid().intValue());
    	  userCardJournal.setVoucherid(Long.valueOf(record.getRegisterid()));
	    
    	  userCardJournalDao.insert(userCardJournal);
    	  
  		 UserAccountJournal accountJournal = new UserAccountJournal();
  		 accountJournal.setJournalDesc(record.getOrderTypeDesc()+Constant.CONSTANTS_VOUCHERNAME_8);
		 accountJournal.setVoucherName(record.getOrderTypeDesc());
		
		 accountJournal.setAcctpageid(null);
		 accountJournal.setAccountid(record.getUserid());
		 accountJournal.setAccountIdno(record.getUserContact());
		 accountJournal.setAccountName(record.getUserName());
		 accountJournal.setVoucherid(record.getRegisterid().toString());
		 accountJournal.setVoucherIdno(record.getRegisterNo());
		 accountJournal.setJournalTotal(new BigDecimal(0));
		
		 accountJournal.setCreateUserid(record.getUserid());
		 accountJournal.setUpdateUserid(record.getUserid());
		 accountJournal.setVoucherDate(now);
		 accountJournal.setVouchertypeid(Constant.CONSTANTS_PAY_ACTION_ID_31);
		 accountJournal.setComment("");
		 accountJournal.setSourceid(Constant.CONSTANTS_PAY_ACTION_ID_32);
		 
		userAccountJournalDao.insert(accountJournal);
		
	    
		return order;
	}
	
	
	
	@Override
	public RegisterOrderExample updateOrder4CardRefoundDoc(RegisterOrder record,UserCardList userCardList,String commont) {
		  RegisterOrderExample order = new RegisterOrderExample();
 
	      registerOrderDao.updateOrderSelective(record);
	    
	      userCardListDao.updateByPrimaryKeySelective(userCardList);

		  UserCardJournal userCardJournal = new UserCardJournal();
		  userCardJournal.setJournalAmount(new BigDecimal(1));
    	  userCardJournal.setCardid(userCardList.getCardid());
    	  userCardJournal.setOwnerid(userCardList.getOwnerid());
    	  userCardJournal.setCarditemid((short)userCardList.getCardtypeid().intValue());
    	  userCardJournal.setJournalDate(new Date());
    	  
    		if (("4".equals(commont)))  {
	    		userCardJournal.setJournalDesc("送药服务,退费");
			}else{
				userCardJournal.setJournalDesc("挂号服务,退费");
			}
    	   // userCardJournal.setGoodsid(record.getGoodsid().intValue());
    	  userCardJournal.setVoucherid(Long.valueOf(record.getRegisterid()));
    	  userCardJournal.setComment(commont);
    	  userCardJournalDao.insert(userCardJournal);
   
		return order;
	}
	
	@Override
	public RegisterOrderExample updateOrder4CardRefound(RegisterOrder record,
			List<UserCardList> userCardList) {
		
			RegisterOrderExample order = new RegisterOrderExample();
		    Date now = new Date();
		    
		    //更新card账户数据
		    String[] amounts = record.getCardJournalAmount().split(",");
		    
		    List<UserCardJournal> userCardJournalList = new ArrayList<UserCardJournal>(); 
		    for (int i = 0; i < userCardList.size(); i++) {
		    	
		    	UserCardList usercCard = userCardList.get(i);
		    	//处理更新卡支付日记账表
				UserCardJournal userCardJournal = new UserCardJournal();
				userCardJournal.setJournalAmount(new BigDecimal(amounts[i]));
		    	userCardJournal.setCardid(usercCard.getCardid());
		    	userCardJournal.setOwnerid(usercCard.getOwnerid());
		    	userCardJournal.setCarditemid((short)usercCard.getCardtypeid().intValue());
		    	userCardJournal.setJournalDate(now);
		    	userCardJournal.setJournalDesc(record.getOrderTypeDesc()+"退费");
		    	userCardJournal.setGoodsid(record.getGoodsid().intValue());
		    	userCardJournal.setVoucherid(Long.valueOf(record.getRegisterid()));
		    	//记录日志
		    	userCardJournalList.add(userCardJournal);
			}
		    //订单日志
		     UserAccountJournal accountJournal = new UserAccountJournal();
			 accountJournal.setJournalDesc(record.getOrderTypeDesc()+Constant.CONSTANTS_VOUCHERNAME_8);
			 accountJournal.setVoucherName(record.getOrderTypeDesc());
			
			 accountJournal.setAcctpageid(null);
			 accountJournal.setAccountid(record.getUserid());
			 accountJournal.setAccountIdno(record.getUserContact());
			 accountJournal.setAccountName(record.getUserName());
			 accountJournal.setVoucherid(record.getRegisterid().toString());
			 accountJournal.setVoucherIdno(record.getRegisterNo());
			 accountJournal.setJournalTotal(new BigDecimal(0));
			
			 accountJournal.setCreateUserid(record.getUserid());
			 accountJournal.setUpdateUserid(record.getUserid());
			 accountJournal.setVoucherDate(now);
			 accountJournal.setVouchertypeid(Constant.CONSTANTS_PAY_ACTION_ID_31);
			 accountJournal.setComment("");
			 accountJournal.setSourceid(Constant.CONSTANTS_PAY_ACTION_ID_32);
			 
			 //写入通用日志
			 userAccountJournalDao.insert(accountJournal);
		     userCardListDao.updateByPrimaryKeySelectiveBatch(userCardList);
		     //写入用卡专用日志
		     userCardJournalDao.insertBatch(userCardJournalList);
		    
			return order;
	}
	
	
	/**
	 * 
	 * 钱包与卡混合支付退费
	 * 
	 */
	@Override
	public RegisterOrderExample updateOrder4WalletAndCardRefound(RegisterOrder  record,UserCardList userCardList) {
		  RegisterOrderExample order = new RegisterOrderExample();
		  int result=-1;
		  Date now = new Date();
	      userCardListDao.updateByPrimaryKeySelective(userCardList);
	      delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_7,record.getUserid());
	     
		  UserCardJournal userCardJournal = new UserCardJournal();
		  userCardJournal.setJournalAmount(new BigDecimal(record.getCardJournalAmount()));
    	  userCardJournal.setCardid(userCardList.getCardid());
    	  userCardJournal.setOwnerid(userCardList.getOwnerid());
    	  userCardJournal.setCarditemid((short)userCardList.getCardtypeid().intValue());
    	  userCardJournal.setJournalDate(now);
    	  userCardJournal.setJournalDesc(record.getOrderTypeDesc()+"退费");
    	  userCardJournal.setGoodsid(record.getGoodsid().intValue());
    	  userCardJournal.setVoucherid(Long.valueOf(record.getRegisterid()));
	    
    	  userCardJournalDao.insert(userCardJournal);
    	  
  		 UserAccountJournal accountJournal = new UserAccountJournal();
  		 accountJournal.setJournalDesc(record.getOrderTypeDesc()+Constant.CONSTANTS_VOUCHERNAME_10);
		 accountJournal.setVoucherName(record.getOrderTypeDesc());
		
		 accountJournal.setAcctpageid(null);
		 accountJournal.setAccountid(record.getUserid());
		 accountJournal.setAccountIdno(record.getUserContact());
		 accountJournal.setAccountName(record.getUserName());
		 accountJournal.setVoucherid(record.getRegisterid().toString());
		 accountJournal.setVoucherIdno(record.getRegisterNo());
		 accountJournal.setJournalTotal(userCardJournal.getJournalAmount().multiply(new  BigDecimal(-1)));
		 accountJournal.setCreateUserid(record.getUserid());
		 accountJournal.setUpdateUserid(record.getUserid());
		 accountJournal.setVoucherDate(now);
		 accountJournal.setVouchertypeid(Constant.CONSTANTS_PAY_ACTION_ID_31);
		 accountJournal.setComment(Constant.CONSTANTS_VOUCHERNAME_8);
		 accountJournal.setSourceid(Constant.CONSTANTS_PAY_ACTION_ID_32);
		userAccountJournalDao.insert(accountJournal);
	    
	    if ( userCardJournal.getJournalAmount().compareTo(record.getRegisterTotal())<0) {
	    	 walletRefound(record, record.getRegisterTotal().subtract(userCardJournal.getJournalAmount()));
		}
		
		return order;
	}
	
	/**
	 * 
	 * 钱包与卡混合支付退费
	 * 
	 */
	@Override
	public RegisterOrderExample updateOrder4WalletAndCardRefound(RegisterOrder record,List<UserCardList> userCardList) {
		

		RegisterOrderExample order = new RegisterOrderExample();
	    Date now = new Date();
	    
	    //更新card账户数据
	    String[] amounts = record.getCardJournalAmount().split(",");
	    BigDecimal total = new BigDecimal(0);
	    List<UserCardJournal> userCardJournalList = new ArrayList<UserCardJournal>(); 
	    for (int i = 0; i < userCardList.size(); i++) {
	    	
	    	UserCardList usercCard = userCardList.get(i);
	    	//处理更新卡支付日记账表
			UserCardJournal userCardJournal = new UserCardJournal();
			userCardJournal.setJournalAmount(new BigDecimal(amounts[i]));
			total  =total.add(new BigDecimal(amounts[i]));
	    	userCardJournal.setCardid(usercCard.getCardid());
	    	userCardJournal.setOwnerid(usercCard.getOwnerid());
	    	userCardJournal.setCarditemid((short)usercCard.getCardtypeid().intValue());
	    	userCardJournal.setJournalDate(now);
	    	userCardJournal.setJournalDesc(record.getOrderTypeDesc()+"退费");
	    	userCardJournal.setGoodsid(record.getGoodsid().intValue());
	    	userCardJournal.setVoucherid(Long.valueOf(record.getRegisterid()));
	    	//记录日志
	    	userCardJournalList.add(userCardJournal);
		}
	    //订单日志
	     UserAccountJournal accountJournal = new UserAccountJournal();
		 accountJournal.setJournalDesc(record.getOrderTypeDesc()+Constant.CONSTANTS_VOUCHERNAME_10);
		 accountJournal.setVoucherName(record.getOrderTypeDesc());
		
		 accountJournal.setAcctpageid(null);
		 accountJournal.setAccountid(record.getUserid());
		 accountJournal.setAccountIdno(record.getUserContact());
		 accountJournal.setAccountName(record.getUserName());
		 accountJournal.setVoucherid(record.getRegisterid().toString());
		 accountJournal.setVoucherIdno(record.getRegisterNo());
		 accountJournal.setJournalTotal(total.multiply(new  BigDecimal(-1)));
		
		 accountJournal.setCreateUserid(record.getUserid());
		 accountJournal.setUpdateUserid(record.getUserid());
		 accountJournal.setVoucherDate(now);
		 accountJournal.setVouchertypeid(Constant.CONSTANTS_PAY_ACTION_ID_31);
		 accountJournal.setComment(Constant.CONSTANTS_VOUCHERNAME_8);
		 accountJournal.setSourceid(Constant.CONSTANTS_PAY_ACTION_ID_32);
		 //写入通用日志
		 userAccountJournalDao.insert(accountJournal);
	     userCardListDao.updateByPrimaryKeySelectiveBatch(userCardList);
	     //写入用卡专用日志
	     userCardJournalDao.insertBatch(userCardJournalList);
	    
	     if (total.compareTo(record.getRegisterTotal())<0) {
	    	 walletRefound(record, record.getRegisterTotal().subtract(total));
		}
	     
		return order;
	}
	
	/**
	 * 钱包支付
	 */
	@Override
	public RegisterOrderExample updateOrder4WalletPaymentDoc(RegisterOrder record ,String times) 
	{
		int result=-1;
		RegisterOrderExample order = new RegisterOrderExample();
		
		UserAccountLedger accountLedger = userAccountLedgerDao.selectByUserId(record.getUserid());
		
		if (null ==accountLedger||accountLedger.getBalanceTotal().compareTo(new BigDecimal(times))<0) {
			//余额不足
			order.setUpdateNum(-2);
			return order;
		}else{
			accountLedger.setBalanceTotal(accountLedger.getBalanceTotal().subtract(new BigDecimal(times)));
			userAccountLedgerDao.updateBalance(accountLedger);
		}
		
		//更新主订单数据
	    result= registerOrderDao.updateOrderSelective(record);
	    
	    delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_2,record.getUserid());
		
	    record.setPayTypeId(Constant.CONSTANTS_PAYMENT_WALLET);
		record.setPayTypeId(Constant.CONSTANTS_PAYMENT_WALLET);
		record.setRegisterTotal(new BigDecimal(times));
	    
		delayUpdateUserAccountJournal(record, record.getUserid(),"");
		
		order.setUpdateNum(result);
		return order;
	}
	
	
	
	
	public void walletRefound(RegisterOrder record,BigDecimal left) {
		   
		UserAccountLedger accountLedger = userAccountLedgerDao.selectByUserId(record.getUserid());
		
		accountLedger.setBalanceTotal(accountLedger.getBalanceTotal().add(left));
	
		userAccountLedgerDao.updateBalance(accountLedger);
	    
  		 UserAccountJournal accountJournal = new UserAccountJournal();
  		 accountJournal.setJournalDesc(record.getOrderTypeDesc()+Constant.CONSTANTS_VOUCHERNAME_10);
		 accountJournal.setVoucherName(record.getOrderTypeDesc());
		
		 accountJournal.setAcctpageid(null);
		 accountJournal.setAccountid(record.getUserid());
		 accountJournal.setAccountIdno(record.getUserContact());
		 accountJournal.setAccountName(record.getUserName());
		 accountJournal.setVoucherid(record.getRegisterid().toString());
		 accountJournal.setVoucherIdno(record.getRegisterNo());
		 accountJournal.setJournalTotal(left.multiply(new  BigDecimal(-1)));
		 accountJournal.setPeriodid(Integer.valueOf(Constant.CONSTANTS_PAYMENT_WALLET));
		 accountJournal.setCreateUserid(record.getUserid());
		 accountJournal.setUpdateUserid(record.getUserid());
		 accountJournal.setVoucherDate( new Date());
		 accountJournal.setVouchertypeid(Constant.CONSTANTS_PAY_ACTION_ID_31);
		 accountJournal.setComment("");
		 accountJournal.setSourceid(Constant.CONSTANTS_PAY_ACTION_ID_33);
		 
		userAccountJournalDao.insert(accountJournal);
}
	
	

	@Override
	public int updateOrder4Quit(RegisterOrder record ) {

		int result=-1; 
		RegisterOrder  currRegisterOrder =registerOrderDao.selectSimpleSingleByOrderId(record.getRegisterid());
		if (currRegisterOrder.getRunstatusid().intValue()==Constant.CONSTANTS_ORDER_RUNSTATUS_ID_3.intValue()) {
			
			if (registerOrderDao.orderAcceptLocked(record.getRegisterid(), 0)) {
				result= registerOrderDao.updateOrderForQuit(record);
				delayOrderActionRecord(record.getRegisterid(),Constant.CONSTANTS_ORDER_ACTION_ID_15,record.getAccepterid());
				//解锁
				registerOrderDao.orderAcceptLocked(record.getRegisterid(), 1);
			}else{
				result= -2;
			}
		
		}else{
			result= -2;
		}
		
		return result;
	}
	
	public IRegisterOrderDao getRegisterOrderDao() {
		return registerOrderDao;
	}

	public void setRegisterOrderDao(IRegisterOrderDao registerOrderDao) {
		this.registerOrderDao = registerOrderDao;
	}

	public IMedicalTreatRecordDao getMedicalTreatRecordDao() {
		return medicalTreatRecordDao;
	}

	public void setMedicalTreatRecordDao(
			IMedicalTreatRecordDao medicalTreatRecordDao) {
		this.medicalTreatRecordDao = medicalTreatRecordDao;
	}

	public IRegisterOrderActionDao getRegisterOrderActionDao() {
		return registerOrderActionDao;
	}

	public void setRegisterOrderActionDao(
			IRegisterOrderActionDao registerOrderActionDao) {
		this.registerOrderActionDao = registerOrderActionDao;
	}

	public IUserAccountLedgerDao getUserAccountLedgerDao() {
		return userAccountLedgerDao;
	}

	public void setUserAccountLedgerDao(IUserAccountLedgerDao userAccountLedgerDao) {
		this.userAccountLedgerDao = userAccountLedgerDao;
	}

	/**
	 * @return the userCardListDao
	 */
	public IUserCardListDao getUserCardListDao() {
		return userCardListDao;
	}

	/**
	 * @param userCardListDao the userCardListDao to set
	 */
	public void setUserCardListDao(IUserCardListDao userCardListDao) {
		this.userCardListDao = userCardListDao;
	}

	public IUserAccountJournalDao getUserAccountJournalDao() {
		return userAccountJournalDao;
	}

	public void setUserAccountJournalDao(
			IUserAccountJournalDao userAccountJournalDao) {
		this.userAccountJournalDao = userAccountJournalDao;
	}

	public IUserLISTDao getUserLISTDao() {
		return userLISTDao;
	}

	public void setUserLISTDao(IUserLISTDao userLISTDao) {
		this.userLISTDao = userLISTDao;
	}

	public IPatientListDao getPatientListDao() {
		return patientListDao;
	}

	public void setPatientListDao(IPatientListDao patientListDao) {
		this.patientListDao = patientListDao;
	}

 

	public IUserCardJournalDao getUserCardJournalDao() {
		return userCardJournalDao;
	}

	public void setUserCardJournalDao(IUserCardJournalDao userCardJournalDao) {
		this.userCardJournalDao = userCardJournalDao;
	}

	public IGoodsPriceListDao getGoodsPriceListDao() {
		return goodsPriceListDao;
	}

	public void setGoodsPriceListDao(IGoodsPriceListDao goodsPriceListDao) {
		this.goodsPriceListDao = goodsPriceListDao;
	}

	@Override
	public List<RegisterOrder> selectOrderState4Timeout(
			RegisterOrderExample example) {
		// TODO Auto-generated method stub
		return registerOrderDao.selectOrderState4Timeout(example);
	}



	/**
	 * @return the registerOrderZScheduleDao
	 */
	public IRegisterOrderZScheduleDao getRegisterOrderZScheduleDao() {
		return registerOrderZScheduleDao;
	}



	/**
	 * @param registerOrderZScheduleDao the registerOrderZScheduleDao to set
	 */
	public void setRegisterOrderZScheduleDao(
			IRegisterOrderZScheduleDao registerOrderZScheduleDao) {
		this.registerOrderZScheduleDao = registerOrderZScheduleDao;
	}

	

	

	
	
	
	
	
}
